#ifndef BLDC_COMMUNICATE_H
#define BLDC_COMMUNICATE_H
#include "ht32f5xxxx_01.h"
#include "usart.h"
#include <string.h>
#define CAN_USART_ID_SIZE   2
#define CAN_SENDFRAME_SIZE  8
#define CAN_RECEFRAME_SIZE  6
#define CAN_USART_SENDSIZE  (CAN_SENDFRAME_SIZE + CAN_USART_ID_SIZE)
#define CAN_USART_RECESIZE  (CAN_RECEFRAME_SIZE + CAN_USART_ID_SIZE)

#define CAN_MASTER_ID       100

typedef uint16_t BLDC_CAN_SendDataFrame[4];
typedef uint8_t BLDC_CAN_RecieveDataFrame[CAN_USART_RECESIZE];

typedef enum{BLDC_Initialized,BLDC_Uninitialized}BLDC_InitStatus_TypeDef;;

typedef struct BLDC_Device
{
    uint16_t ID;
    uint16_t position;
    uint16_t offset_position;
    uint16_t ref_position;
    uint16_t speed;
    uint16_t ref_speed;
    uint16_t moment;
    uint16_t ref_moment;
    uint16_t PD_Kp;
    uint16_t PD_Kd;
    uint16_t current_status;
    BLDC_InitStatus_TypeDef initialized;
    USART_Device *can_device;
    USART_Device *RS485_device;
}BLDC_Device;

typedef struct BLDC_RequestStatusTypeDef
{
    int BLDC_Elbow;
    int BLDC_SWing;
}BLDC_RequestStatusTypeDef;


#define _USART_CAN_SENDDATA(device) \
                                USART_CAN_SendData(device->can_device, device->ID, buffer, 8 );
/**********************************************ERROR CODE********************************************/
#define ERROR_OK                      0
#define ERROR_COULDNT_MATCH_DEVICE   -1
#define ERROR_CAN_MASTER_ID_DISMATCH -2
/****************************************************************************************************/

int USART_CAN_SendData(USART_Device *device, uint16_t ID, void *data, int size);
int BLDC_ParameterSend(BLDC_Device *device, const char *param);
int CAN_RecieveDataHandler(BLDC_CAN_RecieveDataFrame RecieveBuffer, BLDC_Device **device_list);
void PDMA_CH0_1_IRQHandler(void);
void BLDC_RS485_SendCommand(char ch, BLDC_Device *device);

extern const char BLDC_CommandRun[]       ;
extern const char BLDC_CommandStop[]      ;
extern const char BLDC_CommandSetOrigin[] ;
extern int CANRecieveCompleted            ;
extern BLDC_CAN_RecieveDataFrame CANRecieveBuffer;
#endif
